package com.android.vgongyi.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.android.vgongyi.activity.WelcomeActivity;
import com.android.vgongyi.mapper.ImageRequest;
import com.android.vgongyi.net.HttpConnector;
import com.android.vgongyi.service.SaveImage;

public class AsyncImageLoader {
	private static final String TAG = "AsyncImageLoader";
	private Object lock = new Object();
	private boolean mAllowLoad = true;
	private boolean firstLoad = true;
	private int mStartLoadLimit = 0;
	private int mStopLoadLimit = 0;
	private HashMap<String, SoftReference<Drawable>> imageCache;
//	private BlockingQueue queue;
//	private ThreadPoolExecutor executor;
	
	public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
		if (startLoadLimit > stopLoadLimit) {
				return;
			}
		mStartLoadLimit = startLoadLimit;
		mStopLoadLimit = stopLoadLimit;
	}

	public void restore() {
		mAllowLoad = true;
		firstLoad = true;
	}

	public void lock() {
		mAllowLoad = false;
		firstLoad = false;
	}

	public void unlock() {
		mAllowLoad = true;
		synchronized (lock) {
			lock.notifyAll();
		}
	}
	
	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
//		queue = new LinkedBlockingQueue();
//		executor = new ThreadPoolExecutor(1, 10, 180, TimeUnit.SECONDS, queue);
	}
	public Drawable loadDrawable(final Context context,final Integer position, final String imageUrl,final String img_extension,final ImageCallback imageCallback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}
		String fileName = "";
		File file = null;
		if (imageUrl != null && imageUrl.length() != 0) {
	        	fileName = StringUtil.namePicture(imageUrl,img_extension);
	        }
		if(WelcomeActivity.SDCARDISEXIST){
        	 file= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VGongyi/imagefiles", fileName);
        }else {
        	 file = new File(context.getCacheDir(), fileName);
        }
		if(file.exists()){
			
			return Drawable.createFromPath(file.toString());
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl, img_extension);
			}
		};

		new Thread(new Runnable() {
			public void run() {
				try{
					if(!mAllowLoad){
						synchronized (lock) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
					
					if(mAllowLoad && firstLoad){
						Drawable drawable = loadImageFromUrl(context, imageUrl ,img_extension);
						imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
						Message message = handler.obtainMessage(0, drawable);
						handler.sendMessage(message);
					}
					
					if(mAllowLoad && position <= mStopLoadLimit && position >= mStartLoadLimit){
						Drawable drawable = loadImageFromUrl(context, imageUrl ,img_extension);
						imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
						Message message = handler.obtainMessage(0, drawable);
						handler.sendMessage(message);
					}
				}catch (Exception e){
					e.printStackTrace();
				}
				
			}
		}).start();

		return null;
	}

	public static Drawable loadImageFromUrl(Context context, String imageUrl,String img_extension) {
		Drawable drawable = null;
		File file = null;
		if (imageUrl == null)
			return null;
		String fileName = "";

        if (imageUrl != null && imageUrl.length() != 0) {
        	fileName = StringUtil.namePicture(imageUrl, img_extension);
        }
       
        if(WelcomeActivity.SDCARDISEXIST){
        	file= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VGongyi/imagefiles", fileName);
        }else {
        	file = new File(context.getCacheDir(), fileName);
        }
        if (!file.exists() && !file.isDirectory()) {
            try {
                FileOutputStream fos = new FileOutputStream(file);
                ImageRequest imgRq = new ImageRequest(imageUrl);
                HttpConnector http = new HttpConnector(imgRq);
                InputStream is = http.getURLResponse();
                int data = is.read();
                while (data != -1) {
                    fos.write(data);
                    data = is.read();
                }
                fos.close();
                is.close();
                drawable = Drawable.createFromPath(file.toString());
                SaveImage saveImage = new SaveImage(context, imageUrl,img_extension);
    			saveImage.save();
            } catch (IOException e) {
                Log.e(TAG, e.toString());
            } catch (Exception e){
            	e.printStackTrace();
            }
        } else {
            drawable = Drawable.createFromPath(file.toString());
        }
        return drawable;
    }


	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl, String img_extension);
	}

}
